import { _decorator, AudioClip, AudioSource, Component, director, EventTarget, EventTouch, game, native, Node, sys } from 'cc';
import Global from './common/Global';
import { loadScene, onNative } from './common/Utils';
import BaseBean from './model/BaseBean';
import { movieEventTarget } from './home/movie-ticket/TicketTemplate';
const { ccclass, property } = _decorator;

export const mainEventTarget = new EventTarget()

@ccclass('MainController')
export class MainController extends Component {
    @property(Node)
    home: Node = null
    @property(Node)
    fire: Node = null
    
    @property(Node)
    daily: Node = null
    @property(Node)
    ufoAway: Node = null

    @property(Node)
    park: Node = null
    @property(Node)
    market: Node = null
    @property(Node)
    museum: Node = null
    @property(Node)
    movie: Node = null
    @property(Node)
    avatar: Node | null = null;
    // @property(AudioSource)
    // private bgmAudioSource: AudioSource = null

    @property(AudioSource)
    private effectAudioSource: AudioSource = null

    @property(AudioClip)
    private ufoAwayAudioClip: AudioClip = null

    touchId: number = null;
    private onSetWifiStatus(wifiStatus: string) {
        Global.wifiStatus = wifiStatus
        native?.bridge?.sendToNative('log.i', "MainController.ts => onSetWifiStatus Global.wifiStatus = " + Global.wifiStatus)
    }

    private onSetBgmSwitch(bgm: boolean) {
        Global.bgmSwitch = bgm
        // native?.bridge?.sendToNative('log.i', "MainController.ts => onSetBgmSwitch Global.bgmSwitch = " + Global.bgmSwitch)
        // if (Global.bgmSwitch) {
        //     if (!this.bgmAudioSource.playing) {
        //         this.bgmAudioSource.play()
        //     }
        // } else {
        //     if (this.bgmAudioSource.playing) {
        //         this.bgmAudioSource.stop()
        //     }
        // }
    }
    touchStart(event: EventTouch) {
        console.log("touchStart event.getID()", Global.mainTouchId);
    }
    private onHomeClick(event: EventTouch) {
        console.log("onHomeClick event.getID()", Global.mainTouchId);
        if (Global.mainTouchId !== null) return;
        Global.mainTouchId = event.getID();
        loadScene('home', this);
        mainEventTarget?.emit(Global.MESSAGE_RESTORE_IP);
        this.onClickSuccess()
    }

    private onParkClick(event: EventTouch) {
        console.log("onParkClick event.getID()", Global.mainTouchId);
        if (Global.mainTouchId !== null) return;
        Global.mainTouchId = event.getID();
        loadScene('park', this)
        mainEventTarget?.emit(Global.MESSAGE_RESTORE_IP);
        this.onClickSuccess()
    }

    private onClickSuccess(){
        // hideCoinDialog
        //签到金币框在Android中，cocos内部跳转时通知Android
        native.bridge?.sendToNative('hideCoinDialog')
    }

    private onAvatarClick(event: EventTouch) {
        if (Global.mainTouchId !== null) return;
        Global.mainTouchId = event.getID();
        loadScene("userInfo", this);
        mainEventTarget?.emit(Global.MESSAGE_RESTORE_IP);
        this.onClickSuccess()
    }

    private onWifiClick(event: EventTouch) {
        if (Global.mainTouchId !== null) return;
        Global.mainTouchId = event.getID();
        //跳wifi设置
        native?.bridge?.sendToNative('wifi')
    }

    private onSettingClick(event: EventTouch) {
        if (Global.mainTouchId !== null) return;
        Global.mainTouchId = event.getID();
        //设置
        native?.bridge?.sendToNative('settings')
    }

    private onDailyClick(event: EventTouch) {
        if (Global.mainTouchId !== null) return;
        Global.mainTouchId = event.getID();
        // 跳今日必练
        native?.bridge?.sendToNative('daily')
        mainEventTarget?.emit(Global.MESSAGE_RESTORE_IP);
    }

    private onMarketClick(event: EventTouch) {
        console.log("onMarketClick event.getID()", Global.mainTouchId);
        if (Global.mainTouchId !== null) return;
        Global.mainTouchId = event.getID();
        //跳集市
        native?.bridge?.sendToNative('market')
        mainEventTarget?.emit(Global.MESSAGE_RESTORE_IP);
    }

    private onMuseumClick(event: EventTouch) {
        console.log("onMuseumClick event.getID()", Global.mainTouchId);
        if (Global.mainTouchId !== null) return;
        Global.mainTouchId = event.getID();
        //跳科技馆
        native?.bridge?.sendToNative('museum')
        mainEventTarget?.emit(Global.MESSAGE_RESTORE_IP);
    }

    private onMovieClick(event: EventTouch) {
        if (Global.mainTouchId !== null) return;
        Global.mainTouchId = event.getID();
        //跳电影院
        native.bridge?.sendToNative('movie')
        mainEventTarget?.emit(Global.MESSAGE_RESTORE_IP);
    }

    protected onEnable(): void {
        native?.bridge?.sendToNative('log.e', 'MainController.ts onEnable')
        mainEventTarget.on(Global.MESSAGE_SET_WIFi_STATUS, this.onSetWifiStatus, this)
        mainEventTarget.on(Global.MESSAGE_SET_BGM_SWITCH, this.onSetBgmSwitch, this)
        this.home.on(Node.EventType.TOUCH_START, this.touchStart, this)
        this.park.on(Node.EventType.TOUCH_START, this.touchStart, this)
        this.home.on(Node.EventType.TOUCH_END, this.onHomeClick, this)
        this.park.on(Node.EventType.TOUCH_END, this.onParkClick, this)
        this.avatar.on(Node.EventType.TOUCH_END, this.onAvatarClick, this)

        this.market.on(Node.EventType.TOUCH_START, this.touchStart, this)
        this.museum.on(Node.EventType.TOUCH_START, this.touchStart, this)
        this.movie.on(Node.EventType.TOUCH_START, this.touchStart, this)
        this.daily.on(Node.EventType.TOUCH_START, this.touchStart, this)
        if (sys.platform == sys.Platform.ANDROID) {
            native?.bridge?.sendToNative('playingGame', 'false')
            
            onNative(this, mainEventTarget, movieEventTarget);
        }
    }

    protected onDisable(): void {
        native?.bridge?.sendToNative('log.e', 'MainController.ts onDisable')
        mainEventTarget.off(Global.MESSAGE_SET_WIFi_STATUS, this.onSetWifiStatus, this)
        mainEventTarget.off(Global.MESSAGE_SET_BGM_SWITCH, this.onSetBgmSwitch, this)
        this.home.off(Node.EventType.TOUCH_END, this.onHomeClick, this)
        this.park.off(Node.EventType.TOUCH_END, this.onParkClick, this)
        this.home.off(Node.EventType.TOUCH_START, this.onHomeClick, this)
        this.park.off(Node.EventType.TOUCH_START, this.onParkClick, this)
        this.avatar.off(Node.EventType.TOUCH_END, this.onAvatarClick, this)

        this.market.off(Node.EventType.TOUCH_END)
        this.museum.off(Node.EventType.TOUCH_END)
        this.movie.off(Node.EventType.TOUCH_END)
        this.daily.off(Node.EventType.TOUCH_END)
    }

    protected onLoad(): void {
        native?.bridge?.sendToNative('log.e', 'MainController.ts onLoad')
        
        this.loadDailyEntrance()

        //预加载游戏
        Global.preloadGames.forEach(game => {
            const startTime = Date.now(); // 记录预加载开始时间
            director.preloadScene(game, (err, sceneAsset) => {
                const endTime = Date.now(); // 记录预加载结束时间
                const preloadTime = endTime - startTime; // 计算预加载时间

                if (err) {
                    console.error('Failed to preload scene ' + game, err);
                    return;
                }
                console.log(game + ' Scene preloaded in ' + preloadTime + ' ms:', sceneAsset);
            });
        });
        console.log("main onload")
        let header = this.node.getChildByName("Head");
        let controller: any = header.getComponent("Header");
        controller.listenWifiStatus();

        game.addPersistRootNode(this.node)
    }

    start() {
        native?.bridge?.sendToNative('log.e', 'MainController.ts start')
        if (Global.bgmSwitch === true) {
            // this.bgmAudioSource.play()
        }
    }

    update(deltaTime: number) {

    }

    private loadDailyEntrance() {
        if (sys?.platform == sys?.Platform?.ANDROID && Global?.netIsAvailable()) {
            fetch(Global.URL_DAILY_ENTRANCE, { headers: { 'username': Global.deviceId } }).then((response: Response) => {
                return response.text()
            }).then((value) => {
                console.log(value)
                this.handleLevelsJson(value)
            })
        }
    }

    private handleLevelsJson(json: string) {
        try {
            let rawData: BaseBean<Boolean> = JSON.parse(json)
            let showDaily = rawData.data
            if (showDaily) {
                this.daily.active = true
            }
        } catch (error) {

        }
    }

    protected onDestroy(): void {
        console.log("main onDestroy event.getID()", Global.mainTouchId)
        Global.mainTouchId = null;
    }
}


